package com.xcf.controller.base;

import cn.com.xcf.exception.BusinessException;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;


/**
 * 文件导出专用服务类
 */
@Controller("exportFileSupportController")
public class ExportFileSupportController extends BaseController{
    protected Logger logger = LoggerFactory.getLogger(ExportFileSupportController.class);
     
    /**
     * 
     *<p> 导出excel文件，仅支持xls 和xlsx </p>
     * @param templateName  模板名  对应 template/excel下模板的名称   如：transQuery_list.xls
     * @param exportFileName 导出的文件名   如：transQuery_list.xls
     * @param beans
     * @param response
     * @throws BusinessException
     * return void
     * @date 2014-10-9 上午10:19:51
     */
	protected void exportExcel(String templateName, String exportFileName, Map<String, Object> beans,
                               HttpServletResponse response) throws BusinessException {
        try {
        	StringBuilder builder = new StringBuilder("template");
        	builder.append(File.separator).append("excel").append(File.separator);
        	builder.append(templateName);
        	String xlsTemplateFileName = builder.toString();
            logger.info("xlsTemplateFileName ----->{},file:{}",xlsTemplateFileName,exportFileName);
            
            InputStream is = null;
            OutputStream fos = null;
            XLSTransformer transformer = new XLSTransformer();
            is = this.getClass().getClassLoader().getResourceAsStream(xlsTemplateFileName);
            Workbook workbook = transformer.transformXLS(is, beans);
            try {
            	
                response.setHeader("Content-Disposition", "attachment;filename=" +
                        new String(exportFileName.getBytes("utf-8"), "ISO-8859-1")); // 设置应答头信息
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/vnd.xls;charset=utf-8");
                fos = response.getOutputStream();
                workbook.write(fos);
            } catch (UnsupportedEncodingException e) {
                throw new BusinessException(e,"文件编码格式转化错误");
            } catch (IOException e) {
            	 throw new BusinessException(e,"文件读写错误");
            } finally {
                if (is != null) {
                    is.close();
                }
                if (fos != null) {
                    fos.close();
                }
            }
        } catch (Exception e) {
        	 logger.error("系统异常",e);
        	 throw new BusinessException(e,"系统异常");
        }
    }

	
	 /**
	  *<p>  </p>
	  * @param fullFileName
	  * @param dataList
	  * @param response
	  * @throws Exception
	  */
    protected void exportCsv(String fullFileName, List<String> dataList, HttpServletResponse response) throws Exception {
    	try {
	        OutputStream fos = null;
            OutputStreamWriter osw = null;
            BufferedWriter bw = null;
            try {
            	response.setHeader("Content-Disposition", "attachment;filename=" + new String(fullFileName.getBytes("GBK"), "ISO-8859-1")); // 设置应答头信息
                response.setCharacterEncoding("GBK");
                response.setContentType("application/csv;charset=UTF-8");
                fos = response.getOutputStream();
                osw = new OutputStreamWriter(fos, "GBK");
                bw = new BufferedWriter(osw);

                if (dataList != null && !dataList.isEmpty()) {
                    for (String data : dataList) {
                        bw.append(data.replace(",", "\t,")).append("\r");
                    }
                }
            } catch (UnsupportedEncodingException e) {
                throw new BusinessException(e,"文件编码格式转化错误");
            } catch (IOException e) {
            	 throw new BusinessException(e,"文件读写错误");
            } finally {
            	if (bw != null) {
            		bw.close();
                    bw = null;
                }
                if (osw != null) {
                	osw.close();
                    osw = null;
                }
                if (fos != null) {
                	fos.close();
                    fos = null;
                }
            }
        } catch (Exception e) {
        	 throw new BusinessException(e,"系统异常");
        }
    }
}
